package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntBlacklistInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBlacklistInfoService;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-22
 */
@RestController
@Slf4j
@RequestMapping("/admin/merParam/mchntBlackListInfo")
public class BMchntBlacklistInfoController extends BaseController {
    @Resource
    private ResourceLoader resourceLoader;
    @Autowired
    private IUpmpBMchntBlacklistInfoService blacklistInfoService;

    @GetMapping
    public Map<String, Object> findByPage(QueryRequest queryRequest, UpmpBMchntBlacklistInfo blacklistInfo) {
        return getDataTable(blacklistInfoService.findByPage(queryRequest, blacklistInfo));
    }

    @PostMapping()
    public void addMchntBlack(@Valid UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        try {
            blacklistInfoService.addMchntBlack(blacklistInfo);
        } catch (Exception e) {
            String message = e.getMessage();
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @PutMapping()
    public void updateMchntBlack(UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        try {
            blacklistInfoService.updateMchntBlack(blacklistInfo);
        } catch (Exception e) {
            String message = e.getMessage();
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @GetMapping("initFormData")
    public UpmpBMchntBlacklistInfo initFormData(UpmpBMchntBlacklistInfo blacklistInfo) throws RedpException {
        return blacklistInfoService.initFormData(blacklistInfo);
    }


    /**
     * 生成 Excel导入模板
     */
//    @CrossOrigin
    @PostMapping("downloadTemp")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "blacklistImportTemplate.xlsx";

        String  filePath = getClass().getResource("/template/blacklistImportTemplate.xlsx" ).getPath();
        log.info("blacklistImportTemplate filepath:{}",filePath);
        File file = new File(filePath);
        if (file == null) {
            return;
        }
        if (!file.exists()) {
            return;
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            //兼容IE、火狐
            String header = request.getHeader("User-Agent");
            if(header.toLowerCase().contains("firefox")){
                BASE64Encoder base64Encoder = new BASE64Encoder();
                response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?"+(new String(base64Encoder.encode(fileName.getBytes("UTF-8"))))+"?=" );
            }else {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }


    /**
     * 生成 Excel导入模板
     *
     * @param response
     */
    @PostMapping("downloadTemplate")
    public void generateImportTemplate(HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String filename = "导入模板.xls";
            String path = "template/blacklistImportTemplate.xlsx";
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                // jvm的垃圾回收
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

